package com.jay.tools.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.jay.tools.recycler.OnItemClick;

/**
 * author: tanjianpei
 * date: 2019/11/13 013 21:34:55
 * description:
 */
public abstract class BasePopWindow extends PopupWindow {
    protected Context mContext;
    protected OnItemClick<Object> mListener;

    public void setClickListener(OnItemClick<Object> itemClick) {
        mListener = itemClick;
    }

    public BasePopWindow(Context context) {
        mContext = context;
        View v = LayoutInflater.from(context).inflate(getLayoutId(), null);
        setContentView(v);

        calWidthAndHeight(setCustomHeight());

        setFocusable(true);
        setTouchable(true);
        setOutsideTouchable(true);

        setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    dismiss();
                    return true;
                }
                return false;
            }
        });

        initViews(v);
        initData();
        initEvents();
    }

    protected abstract int getLayoutId();

    protected abstract void initViews(View v);

    protected abstract void initData();

    protected abstract void initEvents();

    protected abstract int setCustomHeight();

    /**
     * 计算popupWindow宽度和高度
     */
    private void calWidthAndHeight(int height) {
        if (height == 0)
            height = ViewGroup.LayoutParams.WRAP_CONTENT;
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(height);
    }
}
